package edu.etu.sob.service;

import java.util.ArrayList;
import java.util.List;

import virtuoso.jena.driver.VirtGraph;

import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;

import edu.etu.sob.VirtuosoConstants;

public class GraphManager {

	public VirtGraph createGraph(String graphName) {
		GraphProvider graphProvider = GraphProvider.getInstance();
		if (graphProvider.isGraphAvailable(graphName)) {
			return graphProvider.getGraph(graphName);
		}
		
		VirtGraph graph = new VirtGraph (graphName, VirtuosoConstants.JDBC_VIRTUOSO_URL, VirtuosoConstants.VIRTUOSO_USR, VirtuosoConstants.VIRTUOSO_PWD);

		/*			STEP 2			*/
		/*		Load data to Virtuoso		*/
		graph.clear ();

		String onto = "http://www.co-ode.org/ontologies/pizza/pizza.owl";
		System.out.print ("Begin read from '" + onto + "'  ");
		graph.read(onto, "RDF/XML");
		graphProvider.cacheGraph(graphName, graph);
		System.out.println ("\t\t\t Done.");
		System.out.println("graph.getCount() = " + graph.getCount());
		
		return graph;
	}

	
	public List<Triple> readSuperClasses(String sub, VirtGraph graph) {
		String pred = "http://www.w3.org/2000/01/rdf-schema#subClassOf";
		return readWithSparql(sub, pred, graph);
	}
	
	private List<Triple> readWithSparql(String sub, String pred, VirtGraph graph) {
		Node s = Node.createURI(sub);
		Node p = (pred != null) ? Node.createURI(pred) : Node.ANY;

		ExtendedIterator iter = graph.find(s, p, Node.ANY);
		System.out.println ("\ngraph.find("+s.toString() + "," + p.toString() + ",Node.ANY) \nResult:");
		List<Triple> list = new ArrayList<Triple>();
		for ( ; iter.hasNext() ; ) {
			Triple next = (Triple) (iter.next());
			list.add(next);
		}
		return list;
	}
}
